<template>

  <page-header-wrapper>
    <template #extra>
      <a-button type="danger" @click="batchDeleteUser(selectedRowKeys)">
        批量删除
      </a-button>

      <a-upload list-type="picture" :custom-request="toUploadCheckExcel" :showUploadList="false" accept=".xlsx , .xls">
        <a-button type="primary" :loading="isUpload">
          批量导入
        </a-button>
      </a-upload>
    </template>
    <div class="table-page-search-wrapper">

      <a-card>
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="ID">
                <a-input v-model="search.id" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="邮箱">
                <a-input v-model="search.mail" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="手机号">
                <a-input v-model="search.phone" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="姓">
                <a-input v-model="search.familyName" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="名">
                <a-input v-model="search.username" :allowClear="true"></a-input>
              </a-form-item>
            </a-col>
            <!--            <a-col :xl="6" :lg="8" :md="12" :xs="24">-->
            <!--              <a-form-item label="用户所属社区">-->
            <!--                <a-cascader :options="community" :default-value="[null]"-->
            <!--                            :field-names="{ label: 'name', value: 'id',children:'children' }" :allowClear="false"-->
            <!--                            @change="onCommunityChange"/>-->
            <!--              </a-form-item>-->
            <!--            </a-col>-->
            <a-col :xl="6" :lg="8" :md="12" :xs="24">
              <a-form-item label="每页条数">
                <a-select :default-value="20" @change="handlePageSize">
                  <a-select-option :value="value" v-for="value in pageSizeSelect" :key="value">
                    {{ value }}条/页
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="handleTableChange">查询</a-button>
            </a-col>
          </a-row>
        </a-form>


        <a-table :pagination="pagination" bordered rowKey="id"
                 :row-selection="rowSelection"
                 :data-source="data" :loading="loading"
                 size="small" :columns="columns"
                 @change="handleTableChange"
        >
          <div slot="action" slot-scope="text,record">
            <a-button @click="batchDeleteUser([record.id])" type="link" style="margin-right: 10px">删除</a-button>
            <a-button @click="toShowModal(record)" type="link">详细信息</a-button>
          </div>
        </a-table>
        <a-modal v-model:visible="updateState.state" @ok="toSubmit" @cancel="toCancel" :closable="false" :width="700">
          <div v-if="updateState.data!=null">
            <a-form layout="horizontal" :label-col="{span: 8}"
                    :wrapper-col="{ span: 15 }">
              <a-row :gutter="48">
                <a-col>
                  <a-form-item label="姓">
                    <a-input v-model="updateState.data.familyName" :allowClear="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="名">
                    <a-input v-model="updateState.data.username" :allowClear="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="邮箱">
                    <a-input v-model="updateState.data.mail" :disabled="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="手机号">
                    <a-input v-model="updateState.data.phone" :allowClear="true"></a-input>
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item label="新密码（不填则为不修改）">
                    <a-input v-model="updateState.data.password" :allowClear="true"></a-input>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </a-modal>
      </a-card>
    </div>
  </page-header-wrapper>

</template>

<script>

import {getUser, updateUser, uploadCheckExcel, batchDeleteUser} from "@/api/user";
import {getCommunity} from "@/api/community";

const columns = [
  {
    dataIndex: 'id',
    title: '用户ID',
    key: 'id'
  },
  {
    "title": "用户名",
    customRender(text, e) {
      let str = '';
      str += e.familyName || ' ';
      str += ' ';
      str += e.username || ' '
      return str
    }
  },
  {
    "dataIndex": "mail",
    "title": "邮箱",
  },
  {
    "dataIndex": "phone",
    "title": "手机号",
  },
  {
    "dataIndex": "createAt",
    "title": "创建时间",
  },
  {
    "dataIndex": "updateAt",
    "title": "更新时间",
  },
  // {
  //   "title": "门牌号",
  //   customRender(text, e) {
  //     let str = '';
  //     if (e.tower == undefined && e.unit == undefined) return str
  //     str += (e.tower || '') + ' / ' + (e.unit || '')
  //     if (e.address != null)
  //       str += '/' + e.address
  //     return str
  //   }
  // },
  // {
  //   "dataIndex": "state",
  //   "title": "用户状态",
  //   customRender(text) {
  //     return Number(text) === 1 ? '使用中' : '被禁用'
  //   }
  // },
  {
    "title": "操作",
    scopedSlots: {customRender: 'action'},
  }
]

export default {
  name: "userInfo",
  data() {
    return {
      search: {
        id: '',
        username: '',
        familyName: '',
        mail: '',
        phone: '',
      },
      selectedRowKeys: [],
      data: [],
      columns: columns,
      loading: true,
      pagination: {
        pageSize: 20,
        current: 1,
        total: 0
      },
      isUpload: false,
      updateState: {
        state: false,
        data: null
      },

      pageSizeSelect: [
        10, 20, 30, 50, 100
      ],
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      await this.handleTableChange();
    },
    async handlePageSize(value) {
      this.pagination.pageSize = value;
      await this.handleTableChange();
    },
    async handleTableChange(pagination) {
      this.loading = true;

      if (pagination != null) this.pagination.current = pagination.current

      await this.searchUser();

      this.loading = false;
    },
    handleUserState(value) {
      this.search.state = value
    },
    async searchUser() {
      let _this = this;
      if (this.pagination.current == null) this.pagination.current = 1;
      let data = {};
      for (const searchKey in this.search) {
        if (this.search[searchKey] != null && this.search[searchKey].length > 0) data[searchKey] = this.search[searchKey];
      }

      await getUser({
        current: this.pagination.current,
        size: this.pagination.pageSize,
        ...data
      }).then((res) => {
        console.log(res, 111)
        if (res.status === 200) {
          _this.data = res.data.records
          let set = new Set();
          for (let datum of _this.data) {
            set.add(datum.id);
          }
          this.selectedRowKeys = this.selectedRowKeys.filter((value) => {
            return set.has(value)
          })
          _this.pagination.total = res.data.total
        } else {
          _this.$notification.warning({
            message: res.message
          })
        }
      });
    },
    toShowModal(record) {
      this.updateState.data = JSON.parse(JSON.stringify(record))
      this.updateState.data.password = null;
      this.updateState.state = true;
    },
    toCancel() {
      this.updateState.state = false;
      this.updateState.data = null;
    },
    toSubmit() {
      let info = JSON.parse(JSON.stringify(this.updateState.data));
      delete info.createAt;
      delete info.updateAt;
      delete info.mail;
      this.loading = true;
      if (info.password == null || info.password.trim().length === 0) delete info.password
      updateUser(info).then(async (res) => {
        if (res.status == 200) {
          this.$notification.success({
            message: '修改成功'
          })
          await this.handleTableChange();
          this.toCancel();
        } else {
          this.$notification.error({
            message: res.message || ''
          })
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    async toUploadCheckExcel({file}) {
      if (this.isUpload) return;
      let form = new FormData();
      form.set('file', file);
      this.isUpload = true;
      await uploadCheckExcel(form);
      this.isUpload = false;
      await this.handleTableChange();
    },
    toGetExample() {

    },
    onSelectChange(selectedRowKeys) {
      console.log(selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys;
    },
    batchDeleteUser(idList) {
      let _this = this;
      this.$confirm({
        title: '确认删除？',
        async onOk() {
          await batchDeleteUser({ids: idList.join(',')}).then(() => {
            _this.handleTableChange();
          })
        }
      })
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        hideDefaultSelections: false,

        onChange: this.onSelectChange,
        onSelectAll: this.onSelectAll,
        onSelectInvert: this.onSelectInvert
      };
    },
  },
}
</script>

<style scoped>

</style>